package com.example.servlet;


import com.example.Service.UserService;
import com.example.pojo.User;
import com.google.gson.Gson;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private String message;

    public void init() {
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");

        // Hello
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + message + "</h1>");
        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader br = new BufferedReader(req.getReader());
        StringBuffer sbuffer = new StringBuffer();
        String s = "";
        while ((s = br.readLine()) != null) {
            sbuffer.append(s);
        }
        Gson gson = new Gson();
        User user = gson.fromJson(sbuffer.toString(), User.class);
        Map<String, Object> map = new HashMap<>();
        UserService userService = new UserService();//调用业务逻辑完成登录验证
        int i = userService.reg(user);
        if (i == 0) {
            map.put("code", 500);
            map.put("msg", "注册失败");
        } else {
            map.put("code", 200);
            map.put("msg", "注册成功");
        }
        String json = gson.toJson(map);
        resp.getWriter().append(json);
        System.out.println(json);
    }




    public void destroy() {
    }
}

